<template>
  <div class="page-type">
    <filter-view :atlas-list="classFilterList" @update-list="() => getTypeList()" />
    <a-table
      id="articleTypeTable"
      :row-selection="{ selectedRowKeys: statusState.selectedRowKeys, checkStrictly: false,getCheckboxProps:(record:TypeListData)=>{
      return { disabled: record.level === 1 && record?.type?.length >0 }
    },  onChange: onSelectChange }"
      :expandRowByClick="false"
      :expandedRowKeys="openRowKeys"
      @expandedRowsChange="expandedRowsChangeFunc"
      row-key="id"
      :columns="columns"
      :pagination="false"
      childrenColumnName="type"
      :indentSize="0"
      :defaultExpandAllRows="true"
      :data-source="statusState.typeList"
      :loading="state.loading"
      :rowClassName="(record:TypeListData)=>{
       return record.level === 2 ? 'childBg' : ''
      }"
      :scroll="{ x: 1500 }"
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'name'">
          <span @click="handleOpenKeys">
            <plus-square-outlined v-if="!isOpen" />
            <minus-square-outlined v-else />
            {{ column.title }}
          </span>
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sort'">
          <menu-outlined />
        </template>
        <template v-else-if="column.key === 'type_article_count'">
          <span>
            {{ record.level === 2 ? formatNumber(+record.type_article_count) : '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'name'">
          <a-input
            v-if="statusState.isEdit && record.level === 2"
            :maxlength="30"
            v-model:value="record.name"
            class="w-[170px]"
            placeholder="请输入分类"
          />
          <span v-else>
            <a-tooltip placement="top" color="#fff">
              <template #title>
                {{ record.name }}
              </template>
              <div class="ellipsis-text">{{ record.name }}</div>
            </a-tooltip>
          </span>
        </template>
        <template v-else-if="column.key === 'type_status'">
          <span v-if="record.level === 2">
            <a-switch
              v-model:checked="record.type_status"
              :checkedValue="1"
              :unCheckedValue="2"
              @change="(checked:any) => editStatus(checked, record)"
            />
          </span>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a class="basicColor" @click="handleAddType(record)" v-if="record.level === 1">添加类型</a>
            <a class="basicColor" @click="handleUpdateType(record)" v-if="record.level === 2">
              编辑
              <a-divider type="vertical" />
            </a>
            <a class="basicColor" @click="handleDeleteType(record)" v-if="record.level === 2"> 删除 </a>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 删除对话框 -->
    <modal-view
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>确定要删除该类型吗</span>
    </modal-view>
    <!-- 添加类型对话框 -->
    <modal-view
      :title="statusState.isAdd ? '添加类型' : '编辑类型'"
      v-model:visible="statusState.addTypeVisible"
      okText="确定"
      cancelText="取消"
      :afterClose="afterCloseEdit"
      @confirm="addTypeConfirm"
      @cancel="addTypeCancel"
      :width="511"
    >
      <a-form ref="typeFormRef" :model="typeFormState" :rules="typeFormRules">
        <a-form-item label="所属分类" name="categ_id">
          <a-select
            v-model:value="typeFormState.categ_id"
            :disabled="statusState.isAdd ? false : true"
            placeholder="请选择所属分类"
            class="w-full"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option :value="item.id" v-for="item in classFilterList" :key="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="类型名称" name="type_name">
          <a-textarea
            v-if="statusState.isAdd"
            v-model:value.trim="typeFormState.type_name"
            :maxlength="1000"
            placeholder="请输入类型名称，批量添加多个类型使用逗号“,”分隔"
            :rows="5"
            class="w-full"
          />
          <a-input
            v-else
            v-model:value="typeFormState.type_name"
            placeholder="请输入类型名称，批量添加多个类型使用逗号“,”分隔"
            class="w-full"
          />
        </a-form-item>
        <a-form-item label="序号" name="type_order">
          <a-input-number
            v-model:value.trim="typeFormState.type_order"
            :min="0"
            :max="999999"
            placeholder="请输入序号"
            class="w-full"
          />
        </a-form-item>
        <a-form-item label=" 状态" name="status">
          <a-radio-group v-model:value="typeFormState.type_status">
            <a-radio :value="1" class="mr-[80px]">启用</a-radio>
            <a-radio :value="2">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { formatNumber } from '@/utils/format'
//import Sortable from 'sortablejs'
import FilterView from './components/FilterView.vue'
import { column } from './dataSource'
import type { TypeListData } from '@/types/site/article/articleType'
import { typeState, statusState, type ICopyList } from './state'
import ModalView from '@/components/components/modal/ModalView.vue'
import apis from '@/apis'
import { storage } from '@/utils/storage'
import { message } from 'ant-design-vue'
const {
  site: {
    article_type_list,
    edit_status,
    article_filter_classify_list,
    article_add_type,
    article_update_type,
    article_del_type
  }
} = apis
const typeFormRef = ref()
const columns = ref(column)
const deleteVisible = ref(false)
const siteId = storage.get('siteId')
const classFilterList = ref<ICopyList[]>([])
type Key = string
interface IState {
  loading: boolean
  copyTableData: TypeListData[]
}
const deleteId = ref('')
const openRowKeys = ref<string[]>([])
const isOpen = ref(false)
const state = reactive<IState>({
  loading: false,
  copyTableData: []
})
interface IAddTypeState {
  type_id?: string
  categ_id?: string
  type_name: string
  type_status: number
  site_id?: string | undefined
  type_order?: string
}
//添加类型
const typeFormState = reactive<IAddTypeState>({
  categ_id: '',
  type_name: '',
  type_status: 1,
  type_order: ''
})
const typeFormRules = reactive({
  categ_id: [{ required: true, message: '请选择所属分类' }],
  type_name: [{ required: true, message: '请输入类型名称，批量添加多个类型使用逗号“,”分隔' }],
  type_order: [{ required: true, message: '请输入序号' }]
})
//展开收齐所有行
const handleOpenKeys = () => {
  isOpen.value = !isOpen.value
  if (!isOpen.value) return (openRowKeys.value = [])
  openRowKeys.value = statusState.typeList.map((item: any) => item.id)
}
const expandedRowsChangeFunc = (expandedRows: any) => {
  openRowKeys.value = expandedRows
}
//获取筛选分类接口
const getCopyAtlasList = () => {
  article_filter_classify_list({ site_id: siteId }).then((res: any) => {
    classFilterList.value = res?.categ ?? []
    typeFormState.categ_id = classFilterList.value[0].id
  })
}
//请求
const getTypeList = () => {
  state.loading = true
  typeState.site_id = siteId
  article_type_list(typeState)
    .then((res: any) => {
      statusState.typeList = res?.categ.map((item: any) => {
        for (var key in item) {
          if (Array.isArray(item[key]) && item[key].length === 0) {
            delete item[key]
          }
        }
        return item
      })
      state.loading = false
      console.log('类型列表: ', statusState.typeList)
    })
    .catch(() => {
      state.loading = false
    })
}
const onSelectChange = (rowKeys: Key[]) => {
  console.log('selectedRowKeys changed: ', rowKeys)
  statusState.selectedRowKeys = rowKeys
}
const handleDeleteType = (item: TypeListData) => {
  console.log(item, '删除行data')
  deleteId.value = item.id
  deleteVisible.value = true
  statusState.isEdit = false
}
//添加类型
const handleAddType = (item: any) => {
  console.log('item: ', item)
  statusState.isAdd = true
  statusState.isEdit = false
  statusState.addTypeVisible = true
  typeFormState.categ_id = item.id
}
//编辑
const handleUpdateType = (item: TypeListData) => {
  console.log('item: ', item)
  statusState.addTypeVisible = true
  statusState.isAdd = false
  statusState.isEdit = false
  const { id, name, level, type_picture_count, type_order, ...params } = item
  Object.assign(typeFormState, params)
  typeFormState.type_id = id
  typeFormState.type_name = name
  typeFormState.type_order = type_order
  console.log('typeFormState: ', typeFormState.categ_id)
}
const editStatus = (checked: number, row: TypeListData) => {
  if (!statusState.isEdit) {
    console.log('row: ', row)
    const data = {
      type: 7,
      status: checked,
      id: [row.id]
    }
    console.log('data: ', data.id)
    edit_status(data).then((res: any) => {
      message.success(checked === 1 ? '启用成功' : '禁用成功')
      getTypeList()
    })
  } else {
    row.type_status = checked
  }
}
//重置表单
const afterCloseEdit = () => {
  typeFormRef.value.resetFields()
  typeFormState.categ_id = classFilterList.value[0].id
}
/**
  删除分类对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  article_del_type({ type_id: [deleteId.value] }).then(() => {
    message.success('删除文章类型成功')
    deleteVisible.value = value
    getTypeList()
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
/**
  添加子类对话框事件
 */
const addTypeConfirm = (value: any) => {
  typeFormRef.value.validate().then(() => {
    console.log(typeFormState)
    if (statusState.isAdd) {
      typeFormState.site_id = siteId
      article_add_type(typeFormState).then(() => {
        message.success('新增类型成功')
        statusState.addTypeVisible = value
        getTypeList()
      })
    } else {
      article_update_type(typeFormState).then(() => {
        message.success('编辑类型成功')
        statusState.addTypeVisible = value
        getTypeList()
      })
    }
  })
}
const addTypeCancel = () => {
  typeFormRef.value.resetFields() //关闭弹窗清空表单
  statusState.addTypeVisible = false
}
// watch(
//   () => statusState.addTypeVisible,
//   (val: boolean) => {
//     if (!val) return false
//     getCopyAtlasList()
//   }
// )
//初始化表格拖动
// const initSortable = () => {
//   const sortTable = document.querySelector('#atlasTypeTable tbody') as HTMLElement
//   new Sortable(sortTable, {
//     handle: '.ant-table-row',
//     animation: 150,
//     ghostClass: 'blue-background-class',
//     sort: true,
//     // async
//     onEnd(item) {
//       console.log('item: ', item)
//       let table = Object.assign([], state.typeList)
//       let newTable: any = []
//       //将多维数组展开为一维数组
//       table.forEach((item: any) => {
//         // 如果有子类，将子类也push进去
//         if (item.children && item.children.length > 0) {
//           newTable.push(item)
//           item.children.forEach((i: any) => {
//             i.parentId = item.id
//             newTable.push(i)
//           })
//         } else {
//           newTable.push(item)
//         }
//       })
//       console.log('table: ', table)
//       const sourceObj = newTable[item.oldIndex as number]
//       console.log('sourceObj: ', sourceObj)
//       const targetObj = newTable[item.newIndex as number]
//       console.log('targetObj: ', targetObj)
//       // 判断是否为一级
//       if (!sourceObj.parentId && !targetObj.parentId) {
//         debugger
//         // 操作数据为一级
//         const currRow = newTable.splice(item.oldIndex, 1)[0]
//         newTable.splice(item.newIndex, 0, currRow)
//         let endTable: any = []
//         newTable.forEach((item: any) => {
//           if (!item.parentId) {
//             endTable.push(item)
//           }
//         })
//         state.typeList = endTable
//         console.log('state.typeList: ', state.typeList)
//         state.copyTableData = endTable
//       } else {
//         // 以下为其他不被允许的操作
//         let oneResult = !sourceObj.parentId && targetObj.parentId
//         let TwoResult = sourceObj.parentId && !targetObj.parentId
//         let ThreeResult = sourceObj.parentId && targetObj.parentId && sourceObj.parentId !== targetObj.parentId
//         if (oneResult || TwoResult || ThreeResult) {
//           state.typeList = []
//           // 重新渲染表格
//           nextTick(() => {
//             getTypeList()
//             message.warning('只能在同级之间进行拖拽排序')
//           })
//         }
//       }
//       // // 执行接口更新拖动后的接口
//       // const params = {
//       //   sourceId: source.id, //旧数据id
//       //   destinationId: destination.id, //目标数据id
//       // };
//       // try {
//       //   const res = await api.sort(params);
//       //   if (res.code === 0) {
//       //     message.success(`移动成功`);
//       //   } else {
//       //     message.error(`移动失败`);
//       //   }
//       // } catch (e) {
//       //   message.error(`移动失败`);
//       // } finally {
//       //   emit('updateList')
//       // }
//     }
//   })
// }
onMounted(() => {
  getTypeList()
  getCopyAtlasList()
  // initSortable()
})
</script>
<style lang="less" scoped>
@basicColor: #0083ff;

:deep(.childBg) {
  background-color: #fafafa;
}

// :deep(.ant-table-cell-fix-right) {
//   background: transparent;
// }

:deep(.ant-form-item-label) {
  width: 80px;
  text-align: right;
}

:deep(.ant-form-item-label > label::after) {
  content: '';
}

.page-type {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }

  :deep(.ant-table-cell .ant-table-cell-with-append) {
    display: flex;
    align-items: center;
  }

  :deep(.ellipsis-text) {
    max-width: 154px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }

  .basicColor {
    color: @basicColor;
  }
}
</style>
